package com.yzw.reconnheart;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

import java.net.InetSocketAddress;

/**
 * @Author: YangZhenWei
 * @PROJECT_NAME: nettyTeach
 * @DESCRIPTION: 服务端启动类
 * @USER: root
 * @DATE: 2023/2/8 22:51
 **/
public class AppServerReconnHeart {

    private final int port;

    public AppServerReconnHeart(int port) {
        this.port = port;
    }

    public void run() throws Exception {
        EventLoopGroup group = new NioEventLoopGroup();// io线程池
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(group)
                    .channel(NioServerSocketChannel.class) // 实例化一个通道
                    .localAddress(new InetSocketAddress(port)) // 指定远程的ip和端口
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        /**
                         * 初始化通道，添加通道的处理handler
                         *
                         * @param ch 通道
                         * @throws Exception
                         */
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new HandlerServerReconnHeart());// 添加自定义的handler

                        }
                    });
            //链接获取异步操作的结果值，链接到远程节点，等待链接完成
            ChannelFuture channelFuture = b.bind().sync();
            System.out.println("在"+channelFuture.channel().localAddress()+"监听");

            // 阻塞操作，closeFuture()开启了一个Channel的监听器,这期间channel在进行各种操作
            channelFuture.channel().closeFuture().sync();
        } finally {
            group.shutdownGracefully().sync();
        }
    }

    public static void main(String[] args) throws Exception {
        new AppServerReconnHeart(18080).run();
    }
}
